package com.jc.oms.controller.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jc.cds.model.CustomSupplierGoods;
import com.jc.common.util.*;
import com.jc.ds.model.SupplierGoodsPictureList;
import com.jc.ds.model.SystemLogList;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.LogType;
import com.jc.oms.controller.BaseController;
import com.jc.service.api.yx163.product.ProductService;
import com.jc.service.h5.ShopService;
import com.jc.service.jg.JgService;
import com.jc.service.model.jg.GoodsSendVo;
import com.jc.service.model.jg.RequestBaseModel;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.systemloglist.SystemLogListService;
import com.jc.upload.aliyun.oos.AliyunOssUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

@Controller()
@RequestMapping("product")
public class ProductController extends BaseController {


    @Autowired
    JgService jgService;

    @Autowired
    SystemLogListService systemLogListService;

    @Autowired
    private ProductService productService;

    @SuppressWarnings("finally")
    @RequestMapping(value = "/pull", method = RequestMethod.POST, consumes = "application/json;charset=utf8")
    public @ResponseBody
    Map<String, Object> index(@RequestBody RequestBaseModel model) {
        getLoger().error(DateTimeUtil.getDate(DateTimeUtil.LONG_TIME_FORMAT) + "-------->  接收一条产品信息 :  " + JSONObject.toJSONString(model));
        SystemLogList loglist = new SystemLogList();
        Map<String, Object> _ret = new HashMap<String, Object>();
        try {
            jgService.receiveGoodsData(model);
            _ret.put("code", "10000");
            _ret.put("message", "成功");
            loglist.setConclusion(Conclusion.OK.getName());
        } catch (Exception e) {
            loglist.setConclusion(Conclusion.FAIL.getName());
            if (e != null && StringUtils.isNotBlank(e.getMessage())) {
                loglist.setExceptionMsg(
                        e.getMessage().length() > 500 ? StringUtils.substring(e.getMessage(), 0, 500) : e.getMessage());
            }
            _ret.put("code", "9999");
            _ret.put("message", "推送失败");
            getLoger().error("接收吉贡产品,写入队列时发生异常, {},{}", e.getMessage(), e);
        } finally {
            loglist.setCreateTime(new Date());
            loglist.setLogType(LogType.RECEIVE_JG_PRODUCT.getName());
            List<GoodsSendVo> goodsSendVoList = JSON.parseObject(Base64Util.decode(model.getData()), new TypeReference<List<GoodsSendVo>>() {
            });
            loglist.setBusinessData(JSONObject.toJSONString(goodsSendVoList));
            loglist.setLogTypeName(LogType.RECEIVE_JG_PRODUCT.getDesc());
            loglist.setRespText(JSONObject.toJSONString(_ret));
            systemLogListService.add(loglist, false);
            return _ret;
        }
    }

    @Autowired
    private SupplierGoodsService supplierGoodsService;
    @Autowired
    private SupplierGoodsPictureListService supplierGoodsPictureListService;
    @Autowired
    private ShopService shopService;

    @RequestMapping(value = "/pushShopImg", method = RequestMethod.GET)
    public void pushShopImg() {
        List<CustomSupplierGoods> customSupplierGoods = supplierGoodsService.selectGoodsId();
        for (int x = 0; x < customSupplierGoods.size(); x++) {
            Long id = customSupplierGoods.get(x).getId();
//			Long id = 8140L;
            List<SupplierGoodsPictureList> supplierGoodsPictureLists = supplierGoodsPictureListService.queryAll(new SupplierGoodsPictureList() {{
                setGid(id);
            }});
            String pics = "";
            String details = "";
            for (SupplierGoodsPictureList pictureList : supplierGoodsPictureLists) {
                if (pictureList.getImageType() == 1) {
                    if (StringUtils.isNotBlank(pictureList.getSelfImagePath())) {
                        pics = pics + pictureList.getSelfImagePath() + ";";
                    }
                } else {
                    //详情图
                    if (StringUtils.isNotBlank(pictureList.getSelfImagePath())) {
                        details = details + pictureList.getSelfImagePath() + ";";
                    }
                }
            }
            //推送给商城
            String finalPics = pics;
            String finalDetails = details;
            shopService.pushH5("product/updateProductInfo", new HashMap<String, Object>() {{
                put("productCode", id);
                if (finalPics.length() > 1) {
                    put("pics", finalPics.substring(0, finalPics.length() - 1));
                } else {
                    put("pics", finalPics);
                }
                if (finalDetails.length() > 1) {
                    put("details", finalDetails.substring(0, finalDetails.length() - 1));
                } else {
                    put("details", finalDetails);
                }
            }}, LogType.SHOP_PRO_IMG_UPDATE);
        }
    }

    public static void main(String[] args) {
        String a = "123;";
        System.out.println(a.substring(0, a.length() - 1));
    }

    /**
     * 查询展示商品
     */

    @PostMapping("productQuery")
    @ResponseBody
    public Map<String, Object> productQuery(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = null;

        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("code", "4000");
                result.put("msg", "参数为空~");
            }

        } catch (UnsupportedEncodingException e) {
            result.put("code", "4000");
            result.put("msg", e.getLocalizedMessage());
            e.printStackTrace();
        }
        result = this.productService.queryProduct(params);

        return result;
    }

    /**
     * 查询所有商品
     */
    @PostMapping("allProduct")
    @ResponseBody
    public Map<String, Object> queryAllProduct() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = this.productService.queryAllProduct();
        if (map == null) {
            result.put("code", "4000");
            result.put("msg", "么有数据");
        }
        result.put("code", "10000");
        result.put("data", map);
        return result;
    }

    /**
     * 所有的supplierGoods
     */

    @PostMapping("queryALlSPU")
    @ResponseBody
    public Map<String, Object> queryAllSPU(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        try {
            Map<String, Object> map1 = WebUtils.ReadAsChars(request);
            if (map1.size() == 0) {
                result.put("code", 9999);
                result.put("msg", "必传参数为空");
                return result;
            }
            map = this.productService.queryALLSPU(map1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }


        if (map != null) {
            return map;
        } else {
            result.put("code", "4000");
            result.put("msg", "没有数据~");
        }
        return result;
    }


    /**
     * 根据id查询supplierProduct
     */
    @PostMapping("querySupplierProduct")
    @ResponseBody
    public Map<String, Object> querySupplierProduct(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Subject currentUser = SecurityUtils.getSubject();
        try {
            params = WebUtils.ReadAsChars(request);
            map = this.productService.querySupplierProduct(params);
            if (map != null) {
                result.put("code", "10000");
                result.put("data", map);
            } else {
                result.put("data", "没有数据");
                result.put("code", "4000");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 点击推送商品
     */
    @PostMapping("clickPushGoods")
    @ResponseBody
    public Map<String, Object> clickPushGoods(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        try {
            params = WebUtils.ReadAsChars(request);
            map = this.productService.clickPushGoods(params);
            if (map != null) {
                result.put("data", map);
                result.put("code", "10000");
            } else {
                result.put("msg", "系统异常~~");
                result.put("code", "4000");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }

        return result;

    }

    /***
     * 根据供应商查询产品
     * */
    @PostMapping("queryProductBySupplier")
    @ResponseBody
    public Map<String, Object> queryProductBySupplier(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        try {
            params = WebUtils.ReadAsChars(request);
            map = this.productService.queryProductBySupplier(params);

            if (map != null) {
                return map;
            } else {
                result.put("msg", "暂时无法获取~~~");
                result.put("code", "4000");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;

    }


    /***
     * 根据spu主键删除
     * */
    @PostMapping("deleteProduct")
    @ResponseBody
    public Map<String, Object> deleteProductByGoodsId(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("msg", "删除失败，没有选中~~~~");
                result.put("code", "5000");
                return result;
            }
            map = this.productService.deleteProductById(params);

            if (map != null) {
                result.put("data", map);
                result.put("code", "10000");
            } else {
                result.put("msg", "删除失败了~~~~");
                result.put("code", "5000");
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 前台手动新增商品(修改)
     */
    @PostMapping("handAddProduct")
    @ResponseBody
    public Map<String, Object> handAddProduct(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("code", "5000");
                result.put("msg", "后台没有接收到数据~~~");
            }
            map = this.productService.handAddProduct(params);
            if (map != null) {
                return map;
            } else {
                result.put("code", "5000");
                result.put("msg", "保存失败~");
            }

        } catch (UnsupportedEncodingException e) {
            result.put("code", "5000");
            result.put("msg", "系统异常~");
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 回显编辑产品固定格式
     */
    @PostMapping("proEditShow")
    @ResponseBody
    public Map<String, Object> proEditShow(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();


        try {
            params = WebUtils.ReadAsChars(request);
            if (params.isEmpty()) {
                result.put("code", "4000");
                result.put("msg", "后台没有收到该产品参数~");
                return result;
            }

            result = this.productService.proEditShow(params);


        } catch (UnsupportedEncodingException e) {
            result.put("code", "4000");
            result.put("msg", "系统异常，联系管理员~~");
            e.printStackTrace();
        }

        return result;
    }

    // 上传
    @PostMapping("uploadHeadImage")
    @ResponseBody
    public String uploadHeadImage(String url) {
        String localPath = "/usr/local/static/img/";
        String datestr = DateTimeUtil.getDate(new Date(), "yyyyMMdd");
        try {
            String path = localPath + datestr;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            String extName = UrlUtil.getFileExtension(url);
            String notZipFilePath = path + "/" + name + "." + extName;
            String zipFilePath = path + "/" + "zip" + name + "." + extName;
            ImageUtil.downloadPicture(url, notZipFilePath);
            String localhostPath = ImageUtil.outputQuality(notZipFilePath, 0.5, zipFilePath, new BigDecimal("100"));
            // 上传
            File file = new File(localhostPath);
            AliyunOssUtil util = new AliyunOssUtil();
            String imageURL = util.uploadImg2Oss(file);
            //上传完成删除本地服务器图片
            file.delete();
            File notZipFile = new File(notZipFilePath);
            notZipFile.delete();
//            getLoger().debug("删除服务器图片:"+localhostPath);

            String outImage = util.getImgUrl(imageURL);
            return outImage;
        } catch (Exception e) {
            e.printStackTrace();
//            getLoger().error("压缩上传图片出现错误, 图片源地址: {} , 错误原因: {},{}", remoteUrl, e.getMessage(), e);
        }
        return null;

    }

  /* @PostMapping("upload")
    @ResponseBody
    public Map<String, Object> uploadPic(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();

        String oldName = file.getOriginalFilename();
        System.out.println("文件原名字 = " + oldName);
        System.out.println("file = " + file);

        return result;
    }*/

    /**
     * * 图片文件上传
     * 接受前台图片存到本地 上传到OSS阿里云  获得地址返回前台
     */
    @PostMapping("upload")
    @ResponseBody
    public Map<String, Object> photoUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IllegalStateException, IOException, IOException {
        Map<String, Object> resultMap = new HashMap<>();

        if (file != null) {// 判断上传的文件是否为空
            String path = null;// 文件路径
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            System.out.println("上传的文件原名称:" + fileName);
            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
                // 项目在容器中实际发布运行的根路径
                String realPath = request.getSession().getServletContext().getRealPath("/");
                // 自定义的文件名称
                String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                // 设置存放图片文件的路径
                path = realPath +/*System.getProperty("file.separator")+*/trueFileName;
                // System.out.println("存放图片文件的路径:" + path);
                // 转存文件到指定的路径
                file.transferTo(new File(path));
                //System.out.println("文件成功上传到指定目录下");
                AliyunOssUtil util = new AliyunOssUtil();
                String imageURL = null;
                try {
                    imageURL = util.uploadImg2Oss(new File(path));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //获取oss服务器上的图片的外网地址
                String imgUrl = util.getImgUrl(imageURL);
                String[] split = imgUrl.split("\\?");//
                String s = split[0];
                resultMap.put("data", s);
                resultMap.put("code", 10000);
                resultMap.put("DeleteSinglePic", 20000);
                return resultMap;
            }
        } else {
            resultMap.put("msg", "没有找到相对应的文件");
            resultMap.put("code", 5000);
            return resultMap;

        }
        return resultMap;
    }

    /**
     * 批量删除
     */
    @PostMapping("delList")
    @ResponseBody
    public Map<String, Object> delList(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();

        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("msg", "删除失败，没有选中~~~~");
                result.put("code", "4000");
                return result;
            }
            result = this.productService.delList(params);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 商品的所有分类
     */
    @PostMapping("getAllProductType")
    @ResponseBody
    public Map<String, Object> getAllProductType(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        //productType
        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("msg", "没有收到请求参数");
                result.put("code", "5000");
                return result;
            }
            map = this.productService.getAllProductType(params);
            result.put("code", "10000");
            result.put("data", map);

        } catch (UnsupportedEncodingException e) {
            result.put("msg", e.getLocalizedMessage());
            result.put("code", "5000");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 产品的推送状态
     */
    @PostMapping("getPushStatus")
    @ResponseBody
    public Map<String, Object> getPushStatus(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        //pushStatus
        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("msg", "没有收到请求参数");
                result.put("code", "5000");
                return result;
            }
            map = this.productService.getPushStatus(params);
            result.put("code", "10000");
            result.put("data", map);

        } catch (UnsupportedEncodingException e) {
            result.put("msg", e.getLocalizedMessage());
            result.put("code", "5000");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 商品新增最终版
     */
    @PostMapping("saveGoods")
    @ResponseBody
    public Map<String, Object> saverGoods(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        try {
            params = WebUtils.ReadAsChars(request);
            if (params == null) {
                result.put("msg", "没有收到请求参数");
                result.put("code", "5000");
                result.put("data", "");
                return result;
            }
            map = this.productService.saveGoods(params);

        } catch (UnsupportedEncodingException e) {
            result.put("msg", e.getLocalizedMessage());
            result.put("code", "5000");
            return result;

        }
        return map;
    }

    /**
     * 前台回显数据最终版本
     */
    @PostMapping("backShow")
    @ResponseBody
    public Map<String, Object> backShow(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();


        try {
            params = WebUtils.ReadAsChars(request);
            if (CheckNullUtils.isNull(String.valueOf(params.get("id")))) {
                result.put("data", "");
                result.put("code", "5000");
                result.put("msg", "没有收到数据id，请重试~~");
                return result;
            }

            map = this.productService.backShow(String.valueOf(params.get("id")));

        } catch (UnsupportedEncodingException e) {
            result.put("data", "");
            result.put("code", "5000");
            result.put("msg", e.getLocalizedMessage());
            return result;

        }

        return map;

    }

    /**
     * productId查属性
     */
    @PostMapping("productIdFindAttr")
    @ResponseBody
    public Map<String, Object> productIdFindAttr(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();


        try {
            params = WebUtils.ReadAsChars(request);
            if (CheckNullUtils.isNull(String.valueOf(params.get("productId")))) {
                result.put("data", "");
                result.put("code", "5000");
                result.put("msg", "没有收到数据id，请重试~~");
                return result;
            }

            map = this.productService.productIdFindAttr(String.valueOf(params.get("productId")));

        } catch (UnsupportedEncodingException e) {
            result.put("data", "");
            result.put("code", "5000");
            result.put("msg", e.getLocalizedMessage());
            return result;

        }
        return map;
    }

    /**
     * 所有的spuName
     * */
    @PostMapping("queryAllSpuName")
    @ResponseBody
    public Map<String,Object> queryAllSpuName() {

        return this.productService.queryAllSpuName();
    }
}